﻿using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using SpectrumAnalyser.Data.Common;
using SpectrumAnalyser.Data.Common.Contracts;
using SpectrumAnalyser.ModelObjects;

namespace SpectrumAnalyser.Data.DataBase
{
    public class RepositoryBase<T> : IRepositoryBaseContract<T>, IRepository where T : class, IEntity , new()
    {
        private readonly DbManagerBase _dbManagerBase;

        public RepositoryBase(DbManagerBase dbManager)
        {
            _dbManagerBase = dbManager;
        }

        public Table<T> Query
        {
            get { return _dbManagerBase.GetTable<T>(); }
        }

        public int Save(T entity)
        {
            if (entity.Id > 0)
            {
                var originalEntity = Get(entity.Id);

                PropertyInfo[] props = TypeDescriptor.GetReflectionType(originalEntity).GetProperties();

                foreach (PropertyInfo prop in props)
                {
                    var newValue = prop.GetValue(entity);
                    prop.SetValue(originalEntity, newValue);
                }
            }
            else
            {
                Query.InsertOnSubmit(entity);
            }
            _dbManagerBase.SubmitChanges();
            return entity.Id;
        }

        public virtual T Get(int id)
        {
            //Cast to T. Avoid of mapping base entity property Id.
            T entity = Query.Cast<T>().SingleOrDefault(x => x.Id == id);
            return entity;
        }

        public void Delete(int id)
        {
            Query.DeleteOnSubmit(Get(id));
            _dbManagerBase.SubmitChanges();
        }
    }
}